const WebSocket = require('ws');
const http = require('http');
const express = require('express');
const path = require('path');
const reducers = require('./reducers');
const app = express();

app.use(express.static(path.join(__dirname, '/public')));

const server = http.createServer(app);

const wss = new WebSocket.Server({server: server});

wss.on('connection', function (ws) {

  // stage1: start
  console.log('start service for a client');

  for (let key in reducers) {
    if(reducers.hasOwnProperty(key)) {
      const start = reducers[key]['start'];
      start && start(ws);
    }
  }

  // stage2: message
  ws.on('message', function (message) {
    try {
      const req = JSON.parse(message);
      console.log(req);
      for (let key in reducers) {
        if(reducers.hasOwnProperty(key)) {
          const message = reducers[key]['message'];
          message && message(req, ws);
        }
      }
    } catch (e) {
      console.log('there is a unknow message');
    }
  });

  // stage3: close
  ws.on('close', function () {
    console.log('stop service for a client');
  });

});

server.listen(8000, function listening() {
  console.log('Listening on %d', server.address().port);
});
